<template>
  <div style="padding: 20px">
    <el-card class="box-card" shadow="hover">
      <div class="constant">
        <div class="list">
          <div class="list-cell">
            <div class="cell">
              <div class="title">课程管理>编辑课程</div>
              <div class="line" />
              <div class="title">课程所属行业类目: {{ initParam.categoryName }}</div>
              <!-- 类型-->
              <div class="filter-container">
                课程类型：
                <el-tag v-for="(tag,index) in tags" :key="tag.name" :class="bgindex === index?'active':''"
                  style="cursor: pointer;margin-right: 10px" @click.native="tagClick(tag.cid,index)">
                  {{ tag.name }}
                </el-tag>
              </div>
              <div class="line" />
              <div style="margin-left:80px">
                <div class="kechen">课程名称:
                  <el-input v-model="list.courseName" />
                </div>
                <div class="kechen">课程价格:
                  <el-input type="number" v-model="list.totalAmount" />
                </div>
                <div class="title">课程简介：
                  <editor :init="editorInit" v-model="list.courseDetails" />
                </div>

                <div class="title">课程封面:
                  <el-upload :headers="headers" :action="uploadPath" :show-file-list="false"
                    :before-upload="uploadImgProcess1" :on-progress="uploadImgProcess" :on-success="uploadPicUrl"
                    style="margin-left:100px" accept=".jpg,.jpeg,.png,.gif">
                    <img v-if="list.courseCover!=''&&!imgFlag" :src="list.courseCover"
                      style="width:200px;white-space: nowrap;">
                    <el-progress v-if="imgFlag&&list.courseCover!=''" type="circle" :percentage="imgUploadPercent"
                      style="margin-top:7px;"></el-progress>

                    <i v-if="list.courseCover==''" class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                </div>
                <div class="line" />
                <div v-if="list.categoryName!==''" class="title">课程选项:
                  <el-button style="white-space: nowrap;" type="success" size="mini" round
                    @click="createCourseSection()">创建章节</el-button>
                </div>
                <!--<div class="title">-->
                <!--<el-tree :data="list.adminCourseChild" :props="defaultProps" :default-expand-all="true"/>-->
                <!--</div>-->
                <div v-for="(tag,index) in list.adminCourseChild" :key="tag.id" class="text item">
                  <el-tag size="mini">章></el-tag>{{ tag.sectionName }}
                  <el-button type="primary" size="mini" round @click="handleUpdate(tag)">编辑</el-button>
                  <el-button type="danger" size="mini" round @click="handleDelete(tag)">删除</el-button>
                  <br>
                  <div v-for="(tag1,index1) in list.adminCourseChild[index].children" :key="tag1.id" class="text item">
                    <!-- :data="{FoldPath:'上传目录',SecretKey:'安全验证'}" -->
                    <!--action="http://localhost:8083/admin/course/uploadFile"-->
                    <!-- action="https://mdadmin.czttao.com/admin/course/uploadFile" -->
                    <el-tag type="info" style="  padding: 3px 0; font-size:5px" size="mini">节></el-tag>
                    {{ tag1.sectionName }}
                    <el-button type="primary" size="mini" @click="answer(tag1.id)">视频答题管理</el-button>
                    <div style="display: flex;">
                      <div class="chooseVideo" @click="chooseSource(tag1.id,index,index1)">选择素材</div>
                      <el-upload :id="index1"
                        action="https://mdadmin.czttao.com/admin/course/uploadFile" :data="{sectionId:tag1.id}"
                        :on-progress="uploadVideoProcess" :on-success="handleVideoSuccess" :headers="{
                               timeout: 10000000
                             }" :before-upload="beforeUploadVideo" :show-file-list="false">

                        <div class="update-video-div" @click="uploadVedio(tag1.id,index,index1)">课程上传</div>
                      </el-upload>
                    </div>
                    <video v-if="tag1.sectionContent != ''" :src="tag1.sectionContent" class="update-video"
                      controls="controls">
                    </video>
                    <el-progress v-if="videoFlag == true&&currentIndex == tag1.id" type="circle"
                      :percentage="videoUploadPercent" style="margin-top:7px;"></el-progress>
                  </div>
                  <br>

                  <!-- <el-button type="success" style="margin-left:50px; padding: 3px 0; font-size:5px" size="mini" round plain @click="uploadCourse(tag)">课程上传</el-button> -->

                </div>
                <div class="line" />
              </div>
              <div style="margin-left:250px ; padding: 5px 0">
                <el-button type="primary" round @click="handleCreateOrUpdateCourse()">提交</el-button>
              </div>

            </div>
          </div>
        </div>
      </div>
    </el-card>
    <!-- 新增/编辑课程选项 -->
    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form ref="dataFormCourseSection" :rules="rules" :model="dataFormCourseSection" status-icon
        label-position="top" label-width="100px" style="width: 80%; margin-left:50px;">
        <el-form-item label="章名称" prop="sectionName">
          <el-input v-model="dataFormCourseSection.sectionName" placeholder="章名称" />
        </el-form-item>
        <el-form-item label="章排序" prop="sectionSort">
          <el-input v-model="dataFormCourseSection.sectionSort" placeholder="数字小的排在前面" type="number" />
        </el-form-item>
        <el-form-item label="编辑节">
          <el-table :data="dataFormCourseSection.children" style="width: 100%">
            <el-table-column prop="sectionSort" label="节排序" width="70">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sectionSort" />
              </template>
            </el-table-column>
            <el-table-column prop="sectionName" label="节名称" width="300">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sectionName" />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" circle round plain @click="handleCourseSectionDelete(scope.row)">-
                  删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-button class="button-introduce" style="float:right" size="mini" type="primary" round circle plain
          @click="handleCourseSectionAdd()">+ 增加</el-button>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
        <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button size="mini" v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <chooseSource ref="chooseSource" @submitForm="submitFormSelect" />
  </div>
</template>

<style>
  .update-video-div {
    padding: 15px 10px;
    width: 105px;
    background-color: #1679fb;
    border-radius: 4px;
    color: #fff;
    margin-left: 10px;
    cursor: pointer;
    text-align: center;
    margin-top: 10px;
  }

  .chooseVideo {
    padding: 15px 10px;
    width: 105px;
    background-color: #ff5500;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
    text-align: center;
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .update-video {
    width: 300px;
  }

  .text {
    font-size: 14px;
  }

  .item {
    line-height: 6px;
    margin-left: 50px;
    margin-top: 7px;
  }

  .title {
    margin: 0px auto 10px auto;
    /*text-align: center;*/
    font-weight: bold;
  }

  .uploadPic {
    width: 250px;
    white-space: nowrap;
  }

  .kechen {
    width: 250px;
    white-space: nowrap;
  }

  .constant {
    width: 100%;
  }

  .active {
    background-color: #1e6abc;
    color: white;
  }

  .img {
    margin-top: 20px;
    width: 150px;
    height: 150px;
  }

  .img img {
    width: 100%;
    height: 100%;
  }

  .list {
    width: 100%;
  }

  .list-cell {
    width: 100%;
    line-height: 50px;
  }

  .cell {
    width: 100%;
    /*display: inline-flex;*/
  }

  .set {
    color: deepskyblue;
  }

  .line {
    width: 100%;
    border-bottom: 2px solid #f6f6f6;
  }

  .erweima {
    width: 100%;
    border-bottom: 2px solid #f6f6f6;
  }
</style>

<script>
  import {
    queryCourse,
    updateOrCreateCourse,
    createCourseSection,
    updateCourseSection,
    deleteCourseSection,
    updateSection
  } from '@/api/course'
  import {
    materialadd,
    materiallist,
    materialdelete
  } from '@/api/ad.js'
  import {
    createStorage,
    uploadPath
  } from '@/api/storage'
  import {
    getToken
  } from '@/utils/auth'
  import Editor from '@tinymce/tinymce-vue'
  import Pagination from '@/components/Pagination'
  import TagsView from '../layout/components/TagsView' // Secondary package based on el-pagination
  import chooseSource from './components/chooseSource.vue'

  export default {
    name: 'StoreSet',
    components: {
      TagsView,
      Pagination,
      Editor,
      chooseSource
    },
    data() {
      return {
        zhangId: '',
        sectionId: '',
        showDiv: true,
        imgUploadPercent: '',
        imgFlag: false,
        videoFlag: false,
        //是否显示进度条
        videoUploadPercent: "",
        //显示上传按钮
        videoForm: {
          showVideoPath: ''
        },
        defaultProps: {
          children: 'children',
          label: 'sectionName'
        },
        uploadPath,
        currentIndex: undefined,
        tags: [{
            name: '主要负责人新取证',
            cid: 1
          },
          {
            name: '主要负责人继续教育',
            cid: 2
          },
          {
            name: '管理人员新取证',
            cid: 3
          },
          {
            name: '管理人员继续教育',
            cid: 4
          },
          {
            name: '从业人员新取证',
            cid: 5
          },
          {
            name: '从业人员继续教育',
            cid: 6
          }
        ],
        bgindex: 0, // 默认选择第一项
        updateParam: undefined,
        courseSectionData: undefined,
        dataFormCourse: {
          id: undefined,
          associatedIndustryId: undefined,
          categoryId: undefined,
          sectionName: undefined,
          courseType: undefined,
          courseName: undefined,
          courseDetails: undefined,
          courseCover: undefined,
          examConfigInterval: undefined,
          examConfigScore: undefined,
          deleteMark: undefined,
          createDate: undefined
        },
        dataFormCourseSection: {
          id: undefined,
          pid: undefined,
          courseId: undefined,
          courseType: undefined,
          courseLevel: undefined,
          sectionName: undefined,
          sectionContent: undefined,
          totalDuration: undefined,
          sectionSort: undefined,
          deleteMark: undefined,
          createDate: undefined,
          children: []
        },
        initParam: {
          associatedIndustryId: undefined,
          categoryId: undefined,
          categoryName: undefined,
          courseId: undefined,
          courseType: undefined
        },
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        list: undefined,
        listLoading1: true,
        listLoading: true,
        dialogFormVisible: false,
        downloadLoading: false,
        reqParam: {
          associatedIndustryId: undefined,
          courseId: undefined,
          courseType: undefined
        },
        commentParam: {
          id: undefined,
          page: 1,
          limit: 20,
          userName: undefined,
          starLevel: undefined,
          sort: 'create_date',
          order: 'desc'
        },
        rules: {
          sectionName: [{
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          }]
          // ,
          // sectionSort: [
          //   { required: true, message: '排序不能为空', trigger: 'blur' }
          // ]
        },
        editorInit: {
          language: 'zh_CN',
          convert_urls: false,
          plugins: [
            'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
          ],
          toolbar: [
            'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
            'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
          ],
          images_upload_handler: function(blobInfo, success, failure) {
            const formData = new FormData()
            formData.append('file', blobInfo.blob())
            createStorage(formData)
              .then(res => {
                success(res.data.data.url)
              })
              .catch(() => {
                failure('上传失败，请重新上传')
              })
          }
        }
      }
    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      // 确认素材
      submitFormSelect (data) {
        console.log(data)
        console.log(this.list.adminCourseChild[data.index].children[data.index1])
        let obj = {
          id: this.list.adminCourseChild[data.index].children[data.index1].id,
          sectionContent: data.materialUrl,
          totalDuration: data.totalDuration
        }
        this.updateSection(obj)
      },
      /* 选择素材 */
      chooseSource(id, index, index1) {
        console.log(id)
        let data = {
          id: id,
          index: index,
          index1: index1
        }
        this.$refs.chooseSource.open(data)
      },
      updateSection (data) {
        updateSection(data).then(response => {
          console.log(response)
          if (response.data.code === 200) {
            this.$refs.chooseSource.close()
            this.$notify.success({
              title: '提示',
              message: '添加成功'
            })
            this.getData()
          }
        })
        .catch(() => {})
      },
      /* 上传资源 */
      submitUpload(obj) {
        let data = {
          materialType: 0,
          materialUrl: obj.url,
          materialName: obj.name
        }
        materialadd(data).then(response => {
          console.log(response)
          if (response.data.code === 200) {
            this.$notify.success({
              title: '提示',
              message: '添加成功'
            })
          }
        })
        .catch(() => {})
      },
      answer(id) {
        console.log(id)
        this.$router.push({
          path: '/courseManage/answerQuery',
          query: {
            id: id
          }
        })
      },
      //上传图片成功回调
      handleImgSuccess() {
        if (res.code == 200) {
          this.$notify.success({
            title: '成功',
            message: res.message
          })
        } else {
          this.$notify.error({
            title: '失败',
            message: res.message
          })
        }
        this.getData()
      },
      //上传图片中回调
      uploadImgProcess(event, file, fileList) {
        this.imgFlag = true;
        this.imgUploadPercent = file.percentage.toFixed(1) * 1;
      },
      uploadImgProcess1(event, file, fileList) {
        this.imgFlag = true;
      },
      //上传图片成功
      uploadPicUrl: function(response) {
        this.list.courseCover = response.data.url;
        this.imgUploadPercent = 100;
        this.imgFlag = false;
        if (res.code == 200) {
          this.$notify.success({
            title: '成功',
            message: res.message
          })
        } else {
          this.$notify.error({
            title: '失败',
            message: res.message
          })
        }
        this.getData()
      },
      //上传视频
      uploadVedio(sectionId, index, index1) {
        this.sectionId = sectionId;
        this.currentIndex = this.sectionId;
        console.log(this.sectionId)
      },
      //上传视频前回调
      beforeUploadVideo(file) {
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file
            .type) == -1) {
          // alert("请上传正确的视频格式");
          this.$notify.error({
            title: '失败',
            message: "请上传正确的视频格式"
          })
          return false;
        }
      },
      //进度条
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = file.percentage.toFixed(1) * 1;
      },
      //上传成功回调
      handleVideoSuccess(res, file) {
        // alert(res.message)
        console.log(file)
        console.log('res')
        console.log(res)
        if (res.code == 200) {
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          this.$confirm('是否添加到素材里面?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.submitUpload({
              url: res.data.sectionContent,
              name: file.name
            })
          }).catch(() => {})
        } else {
          this.$notify.error({
            title: '失败',
            message: res.message
          })
        }
        this.getData()
        this.videoFlag = false;
        this.videoUploadPercent = 0;
      },
      restListParam() {
        this.list = {
          categoryName: '', // 课程所属行业类目
          courseName: '', // 课程名称
          courseDetails: '', // 课程简介
          courseCover: '', // 课程封面
          adminCourseChild: [] // 查看课程
        }
      },
      resetFormCourseSection() {
        this.dataFormCourseSection = {
          id: undefined,
          pid: undefined,
          courseId: this.list.id, // 新增得到id
          courseType: this.list.courseType, //  新增得到courseType
          courseLevel: undefined,
          sectionName: undefined,
          sectionContent: undefined,
          totalDuration: undefined,
          sectionSort: undefined,
          deleteMark: undefined,
          createDate: undefined,
          children: []
        }
      },
      // 标签类事件
      tagClick(cid, index) {
        // if (this.bgindex === index) {
        //   this.bgindex = -1
        //   this.reqParam.courseType = 1
        //   this.getData()
        // } else {
        this.bgindex = index
        this.reqParam.courseType = cid
        this.initParam.courseType = cid
        this.getData()
        // }
      },

      // 初始化参数
      init: function() {
        // this.restListParam()
        if (this.$route.query.associatedIndustryId === undefined || this.$route.query.associatedIndustryId == null) {
          return
        }
        if (this.$route.query.courseType !== undefined || this.$route.query.courseType != null) {
          this.reqParam.courseType = this.initParam.courseType = this.$route.query.courseType
          this.bgindex = this.$route.query.courseType - 1
        } else {
          this.initParam.courseType = this.reqParam.courseType = 1 // 初始化页面时，courseType=1
          this.bgindex = 0
        }
        this.initParam.associatedIndustryId = this.$route.query.associatedIndustryId
        this.initParam.categoryId = this.$route.query.categoryId
        this.initParam.categoryName = this.$route.query.categoryName
        if (this.$route.query.courseId !== undefined || this.$route.query.courseId != null) {
          this.initParam.courseId = this.reqParam.courseId = this.$route.query.courseId
        }
        this.reqParam.associatedIndustryId = this.initParam.associatedIndustryId

        this.getData()
      },
      getData() {
        this.listLoading = true
        this.list = [] // 重置课程选项
        queryCourse(this.reqParam)
          .then(response => {
            this.list = response.data.data
            if (this.list === undefined) {
              this.restListParam() // 重置参数，目的是为了加载页面有默认值
            }
            this.listLoading = false
          })
          .catch(() => {
            this.list = undefined
            this.listLoading = false
          })
      },
      handleUpdate(tag) {
        this.dataFormCourseSection = Object.assign({}, tag)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      },
      createCourseSection() {
        if (this.list.id === '' || this.list.id === null || this.list.id === undefined) {
          this.$confirm('清先添加课程并提交', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        } else {
          this.resetFormCourseSection()
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
        }
      },
      handleCreateOrUpdateCourse() {
        this.list.associatedIndustryId = this.initParam.associatedIndustryId
        this.list.categoryId = this.initParam.categoryId
        this.list.categoryName = this.initParam.categoryName
        this.list.courseType = this.initParam.courseType
        updateOrCreateCourse(this.list)
          .then(response => {
            this.initParam.courseId = this.dataFormCourseSection.courseId = response.data.data
              .id // 得到id，为了新增课程选项 courseId
            this.dataFormCourseSection.courseType = response.data.data.courseType // 得到id，为了新增课程选项 courseId
            // this.initParam.courseId = response.data.data.id // 初始化页面需要的参数
            //跳转查询页
            // this.queryCourse();
            // this.getData()
            this.$notify.success({
              title: '成功',
              message: '执行成功'
            })
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.message
            })
          })
      },

      handleCourseSectionAdd() {
        const children = {
          sectionSort: '',
          sectionName: '',
          courseLevel: '2',
          courseId: this.dataFormCourseSection.courseId,
          courseType: this.dataFormCourseSection.courseType
        }
        this.dataFormCourseSection.children.push(children)
      },
      handleCourseSectionDelete(row) {
        const index = this.dataFormCourseSection.children.indexOf(row)
        this.dataFormCourseSection.children.splice(index, 1)
        if (row.id != null) { // 判断如果id=null不请求
          this.handleDelete(row)
        }
      },
      handleDelete(row) {
        deleteCourseSection(row)
          .then(response => {
            this.getData()
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.message
            })
          })
      },
      createData() {
        createCourseSection(this.dataFormCourseSection)
          .then(response => {
            this.getData()
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '创建成功'
            })
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.message
            })
          })
      },
      updateData() {
        updateCourseSection(this.dataFormCourseSection)
          .then(() => {
            this.getData()
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '更新成功'
            })
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.message
            })
          })
      },
      uploadSectionContent: function(response) {
        this.dataFormCourseSection.sectionContent = response.data.url
        console.log(response.data)
      },
      queryCourse() {
        this.$router.push({
          path: '/courseManage/queryCourse',
          query: {
            courseId: this.list.id,
            associatedIndustryId: this.initParam.associatedIndustryId,
            categoryId: this.initParam.categoryId,
            categoryName: this.initParam.categoryName,
            courseType: this.initParam.courseType
          }
        })
      }
    }
  }
</script>
